package com.cxrj.pqm.utils;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;

@Controller
public class WxCodeController {

	private final String APPID = "wx3cb34d014536a021";

	private final String SECRET = "f5ac931f8126646268b3dfe3bb9aa836";

	@RequestMapping(value = "getCode")
	@ResponseBody
	public void getCode(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if (request.getSession().getAttribute("openid") != null) {
			return;
		}
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");
		// 这里要将你的授权回调地址处理一下，否则微信识别不了
		String redirect_uri = URLEncoder.encode(request.getContextPath() + File.separator + "../getOpenId/", "UTF-8");
		// 简单获取openid的话参数response_type与scope与state参数固定写死即可
		StringBuffer url = new StringBuffer(
				"https://open.weixin.qq.com/connect/oauth2/authorize?redirect_uri=" + redirect_uri + "&appid=" + APPID + "&response_type=code&scope=snsapi_base&state=1#wechat_redirect");
		response.sendRedirect(url.toString());// 这里请不要使用get请求单纯的将页面跳转到该url即可
	}

	@RequestMapping(value = "getOpenId")
	@ResponseBody
	public void getOpenId(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");
		String code = request.getParameter("code");// 获取code
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("secret", SECRET);
		params.put("appid", APPID);
		params.put("grant_type", "authorization_code");
		params.put("code", code);
		String result = HttpGetUtil.httpRequestToString("https://api.weixin.qq.com/sns/oauth2/access_token", params);
		JSONObject jsonObject = JSONObject.parseObject(result);
		String openid = jsonObject.get("openid").toString();
		request.getSession().setAttribute("openid", openid);
	}
}
